const express = require('express');
const moment = require('moment');
const AccountModel = require('../../models/AccountModel');
const checkLoginMiddleware = require('../../Middleware/checkLoginMiddleware');


const router = express.Router();


router.get('/', (req, res, next) => {

  res.redirect(`/account/${req.session._id}`);
})

// 记账本列表
router.get('/account/:u_id', checkLoginMiddleware, function (req, res, next) {

  AccountModel.find({ u_id: req.params.u_id })
    .sort({ time: -1 })
    .then((data) => {
      res.render('list', { accounts: data, moment: moment, u_id: req.params.u_id });
    });
});

// 添加记录
router.get('/account/create/:u_id', checkLoginMiddleware, function (req, res, next) {
  res.render('create', { u_id: req.params.u_id });
});

router.post('/account', checkLoginMiddleware, (req, res, next) => {
  // 写入信息
  // 时间戳(秒)
  AccountModel.create({
    ...req.body,
    time: moment(req.body.time).unix(),
  }).then(() => {
    res.render('success', { msg: '添加成功~', url: `/account/${req.body.u_id}` });
  }, () => {
    res.render('fail', { msg: '插入失败~', url: `/account/${req.body.u_id}` });
  })
});

router.get('/account/:_id/:u_id', checkLoginMiddleware, (req, res, next) => {
  // 获取id
  let _id = req.params._id;
  let u_id;
  AccountModel.findOne({ _id })
    .then((data) => {
      u_id = data.u_id;
    });
  AccountModel.deleteOne({ _id: _id })
    .then(data => {
      console.log(data);
      res.render('success', { msg: '删除成功~', url: `/account/${req.params.u_id}` });
    })
  // // 删除
})

module.exports = router;
